<?php

class DateTimeBehavior extends CActiveRecordBehavior {
	
	public $exception=array();
	
	public function beforeSave($event){
		Yii::trace(get_class($this->getOwner()).'.'.get_class($this).'.beforeSave()','app.components.behaviors');
		foreach($this->getOwner()->metadata->tableSchema->columns as $columnName => $column){
			
			if (!strlen($this->getOwner()->{$columnName})) {$this->getOwner()->{$columnName}=null;continue;}
			
			if (in_array($columnName,$this->exception)) continue;
			
			if ($column->dbType == 'date'){
				$this->getOwner()->{$columnName} = date('Y-m-d', CDateTimeParser::parse($this->getOwner()->{$columnName}, Yii::app()->locale->dateFormat));
			}elseif ($column->dbType == 'datetime'){
				if (strlen($this->getOwner()->{$columnName})==10) $this->getOwner()->{$columnName}=$this->getOwner()->{$columnName}.' 0:00:00';
				$this->getOwner()->{$columnName} = date('Y-m-d H:i:s', CDateTimeParser::parse($this->getOwner()->{$columnName}, Yii::app()->locale->dateFormat.' '.Yii::app()->locale->timeFormat));
			}
		}
	}
	        
	public function afterFind($event){
		Yii::trace(get_class($this->getOwner()).'.'.get_class($this).'.afterFind()','app.components.behaviors');
		foreach($this->getOwner()->metadata->tableSchema->columns as $columnName => $column){
			
			if (!strlen($this->getOwner()->{$columnName})) continue;
			
			if (in_array($columnName,$this->exception)) continue;
			
			if ($column->dbType == 'date'){
					$this->getOwner()->{$columnName} = Yii::app()->dateFormatter->formatDateTime(
					CDateTimeParser::parse($this->getOwner()->{$columnName}, 'yyyy-MM-dd'),'medium',null);
			}elseif ($column->dbType == 'datetime'){
					$this->getOwner()->{$columnName} = Yii::app()->dateFormatter->formatDateTime(
					CDateTimeParser::parse($this->getOwner()->{$columnName}, 'yyyy-MM-dd hh:mm:ss'));
			}
		}
	}

}